import axios from 'axios'

const service = axios.create({
    baseURL: process.env.VUE_APP_BASE,
    timeout: 300000
});

service.interceptors.request.use(config => {
    return config;
}, error => {
    Promise.reject(error);
})

service.interceptors.response.use(
    response => {
        if(response.data.code == 200) {
            return response.data.data;
        } else {
            if(response.data.code == 401) {
                window.location.href = `${process.env.VUE_APP_BASE}access?page=/${process.env.VUE_APP_OUTPUT_DIR}/index.html&appid=`+sessionStorage.getItem("state");
            } else {
                return Promise.reject(response.data)
            }
        }
    },
    error => {
        return Promise.reject(error);
    }
)

export const axiosAll = function axiosAll(promiseList) {
    return axios.all(promiseList);
}

export const getQueryObject = function (url) {
    url = url == null ? window.location.search : url;
    var search = url;
    var obj = {};
    var reg = /([^?#&=]+)=([^&]*)/g;
    search.replace(reg, function(rs, $1, $2) {
        var name = decodeURIComponent($1);
        var val = decodeURIComponent($2);
        val = String(val);
        obj[name] = val;
        return rs;
    });
    return obj;
}


export const setAuthorization = function(token) {
    if(token) {
        axios.defaults.headers.common['Authorization'] = token;
        sessionStorage.setItem("Authorization", token);
    } else {
        if(process.env.VUE_APP_MODE === 'web') {
            if(process.env.NODE_ENV !="production") {
                sessionStorage.setItem("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb21wYW55SWQiOjEsIm9wZW5pZCI6Im82cmNTMVZOQTduS2Vjb1NoMTZQNzh5MEtOeFkiLCJhcHBpZCI6Ind4NjBiNzgyYjFkZTlmMzAzMiJ9.SkUb_orU6c0K5w1f0qzOFnPkHY-rDde-l7kLId2H--w");
            } else {
                alert('错误发生了')
            }
        } else {
            sessionStorage.setItem("Authorization", "eyJ0eXAiOiJKV1QiLCJhbGciOiJIUzI1NiJ9.eyJjb21wYW55SWQiOjEsIm9wZW5pZCI6Im82cmNTMVZOQTduS2Vjb1NoMTZQNzh5MEtOeFkiLCJhcHBpZCI6Ind4NjBiNzgyYjFkZTlmMzAzMiJ9.SkUb_orU6c0K5w1f0qzOFnPkHY-rDde-l7kLId2H--w");
        }
        
        if(sessionStorage.getItem("Authorization")) {
            axios.defaults.headers.common['Authorization'] = sessionStorage.getItem("Authorization");
        } else {
            var href = window.location.href;
            var origin = window.location.origin;
            var url = href.replace(origin, "");

            window.location.href = `${process.env.VUE_APP_BASE}access?page=${url}&appid=`+sessionStorage.getItem("state");
        }
    }
}

export default service;
